﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class TriggerCollisionExitAdv : TriggerBase
{
    public LayerMask triggerLayer;
    public ETriggerDirection triggerDirection;
    float heightWidth;
    float widthHeight;

    public override void InitTrigger()
    {
        base.InitTrigger();
        heightWidth = GetComponent<BoxCollider2D>().bounds.size.y / GetComponent<BoxCollider2D>().bounds.size.x;
        widthHeight = GetComponent<BoxCollider2D>().bounds.size.x / GetComponent<BoxCollider2D>().bounds.size.y;
    }


    void OnTriggerExit2D(Collider2D collider2d)
    {

        Debug.LogError("collider2d " + collider2d.gameObject.name);
        if (Util.IsInLayerMask(collider2d.gameObject.layer, triggerLayer))
        {
            JudgeDir(collider2d.transform);
        }
    }

    void OnCollisionExit2D(Collision2D collision)
    {
        Debug.LogError("Collision2D " + collision.gameObject.name);
        if (Util.IsInLayerMask(collision.gameObject.layer, triggerLayer))
        {
            JudgeDir(collision.transform);
        }
    }

    private void JudgeDir(Transform triggerTsf)
    {
        Vector3 heading = triggerTsf.position - transform.position;
        float distance = heading.magnitude;
        Vector3 direction = heading / distance;
        ETriggerDirection curDir = ETriggerDirection.None;

        if (Mathf.Abs(direction.x / widthHeight) > Mathf.Abs(direction.y / heightWidth))
        {
            if (Mathf.Sign(direction.x) == 1)
            {
                print("exit From Right");
                curDir = ETriggerDirection.Right;
            }

            if (Mathf.Sign(direction.x) == -1)
            {
                print("exit From Left");
                curDir = ETriggerDirection.Left;
            }
        }
        if (Mathf.Abs(direction.x / widthHeight) < Mathf.Abs(direction.y / heightWidth))
        {
            if (Mathf.Sign(direction.y) == 1)
            {
                print("exit From Top");
                curDir = ETriggerDirection.Top;
            }
            if (Mathf.Sign(direction.y) == -1)
            {
                print("exit From Bot");
                curDir = ETriggerDirection.Bottom;
            }
        }
        if (curDir == triggerDirection)
            OnTrigger();
    }

}
